<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我们的恋爱清单 | 总有些惊奇的际遇 比方说当我遇见你</title>
    <link href="/Style/css/font-awesome.min.css" rel="stylesheet">
    <script src="/Style/js/tailwindcss.js"></script>
    <style>
        /* 导航栏样式 */
        nav {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            z-index: 100;
            transition: all 0.3s ease;
            background-color: white;
        }

        .nav-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 60px;
        }

        .logo {
            color: #333;
            font-size: 1.2rem;
            font-weight: bold;
            text-decoration: none;
        }

        .nav-links {
            display: flex;
            list-style: none;
        }

        .nav-links li {
            margin-left: 25px;
        }

        .nav-links a {
            color: #333;
            text-decoration: none;
            font-size: 0.9rem;
            transition: color 0.3s ease;
        }

        .nav-links a:hover, .nav-links a.active {
            color: #e94c89;
            font-weight: 500;
        }

        .user-area {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid white;
            cursor: pointer;
        }

        /* 移动端菜单按钮 */
        .mobile-menu-button {
            display: none;
            background: none;
            border: none;
            font-size: 1.5rem;
            color: #333;
            cursor: pointer;
        }

        /* 移动端菜单 */
        .mobile-menu {
            display: none;
            padding: 15px 20px;
            background-color: white;
            border-top: 1px solid #f0f0f0;
        }

        .mobile-menu a {
            display: block;
            color: #333;
            text-decoration: none;
            padding: 10px 0;
            border-bottom: 1px solid #f0f0f0;
        }

        .mobile-menu a:last-child {
            border-bottom: none;
        }

        .mobile-menu a:hover, .mobile-menu a.active {
            color: #e94c89;
        }

        /* 基础样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: #f9f5f8;
            color: #333;
            line-height: 1.6;
            padding-top: 60px;
        }

        .central {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        .central-800 {
            max-width: 800px;
        }

        .title {
            text-align: center;
            padding: 40px 0 20px;
        }

        .title h1 {
            color: #e94c89;
            font-weight: 300;
            font-size: 2.2rem;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
        }

        .relationship-status {
            text-align: center;
            margin-bottom: 30px;
            padding: 15px;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .relationship-status .couple-info {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
            margin: 10px 0;
        }

        .avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #e94c89;
        }

        .days-together {
            color: #666;
            font-size: 0.9rem;
            margin-top: 5px;
        }

        .anniversary-date {
            color: #e94c89;
            font-weight: 500;
            margin: 10px 0;
            display: block;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 30px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background-color: #e94c89;
            color: white;
        }

        .btn-primary:hover {
            background-color: #d03a76;
            transform: translateY(-2px);
        }

        .btn-outline {
            background-color: transparent;
            border: 1px solid #e94c89;
            color: #e94c89;
        }

        .btn-outline:hover {
            background-color: #fce4ec;
        }

        /* 卡片样式 */
        .card {
            background-color: white;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
            padding: 25px;
            margin-bottom: 30px;
        }

        /* 清单样式 - 强制显示操作按钮 */
        .lovelist {
            list-style: none;
        }

        .cike {
            padding: 15px 10px;
            border-bottom: 1px solid #f0f0f0;
            position: relative;
        }

        .cike:hover {
            background-color: #fcf4f7;
        }

        .cike:last-child {
            border-bottom: none;
        }

        /* 内容区样式 */
        .cike .content {
            flex: 1;
            transition: all 0.3s ease;
            padding: 5px 0; /* 增加内边距提升触摸体验 */
        }

        /* 操作区基础样式 */
        .actions {
            display: flex;
            gap: 10px;
            opacity: 1;
            visibility: visible;
        }

        .completed .content {
            text-decoration: line-through;
            color: #999;
        }

        .iconfont {
            font-size: 1.2rem;
        }

        .icon-chenggong2 {
            color: #e94c89;
        }

        .icon-weibiaoti1 {
            color: #333;
        }

        .action-btn {
            background: none;
            border: none;
            cursor: pointer;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            padding: 0;
            margin: 0;
            transition: all 0.2s ease;
        }

        /* 为每个按钮设置鲜明颜色 */
        .toggle-complete {
            color: #28a745 !important;
            background-color: rgba(40, 167, 69, 0.1);
        }

        .edit-item {
            color: #007bff !important;
            background-color: rgba(0, 123, 255, 0.1);
        }

        .delete-item {
            color: #dc3545 !important;
            background-color: rgba(220, 53, 69, 0.1);
        }

        /* 悬停效果增强 */
        .action-btn:hover {
            transform: scale(1.2);
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }

        /* 图片预览样式 */
        .image-preview {
            margin-top: 10px;
            padding: 10px;
            border-radius: 8px;
            background-color: #f9f9f9;
            display: none;
        }

        .image-preview img {
            max-width: 100%;
            border-radius: 5px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        /* 表单样式 */
        .add-form {
            margin-bottom: 30px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .form-control {
            flex: 1;
            min-width: 250px;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 30px;
            font-size: 1rem;
            transition: border-color 0.2s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: #e94c89;
        }

        .form-actions {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .share-checkbox {
            display: flex;
            align-items: center;
            gap: 5px;
            color: #666;
        }

        /* 统计和筛选 */
        .stats-filter {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .stats {
            color: #e94c89;
            font-weight: 500;
        }

        .filter-btn {
            background: none;
            border: 1px solid #ddd;
            padding: 5px 12px;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .filter-btn.active {
            background-color: #e94c89;
            color: white;
            border-color: #e94c89;
        }

        /* 模态框样式 - 优化图片展示和按钮显示 */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
            overflow-y: auto; /* 允许垂直滚动 */
            padding: 20px 0; /* 添加上下内边距 */
        }

        .modal.show {
            opacity: 1;
            visibility: visible;
        }

        .modal-content {
            background-color: white;
            border-radius: 15px;
            width: 90%;
            max-width: 500px;
            padding: 25px;
            transform: translateY(-20px);
            transition: transform 0.3s ease;
            position: relative;
            max-height: 90vh; /* 限制最大高度为视口的90% */
            display: flex;
            flex-direction: column; /* 使用flex布局 */
        }

        .modal.show .modal-content {
            transform: translateY(0);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-shrink: 0; /* 不缩小 */
        }

        .modal-title {
            font-size: 1.3rem;
            color: #e94c89;
        }

        .close-modal {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #999;
        }

        .modal-body {
            margin-bottom: 25px;
            flex-grow: 1; /* 允许内容区域增长 */
            overflow-y: auto; /* 内容过多时可滚动 */
            padding-right: 10px; /* 预留滚动条空间 */
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            padding-top: 15px;
            border-top: 1px solid #f0f0f0;
            flex-shrink: 0; /* 不缩小，确保按钮始终可见 */
        }

        /* 编辑弹窗图片样式 - 等比例缩放优化 */
        .edit-image-container {
            margin: 15px 0;
            border-radius: 8px;
            overflow: hidden;
            background-color: #f9f9f9;
            padding: 15px;
            text-align: center;
            position: relative;
        }

        .edit-modal-image {
            max-width: 100%; /* 最大宽度不超过容器 */
            max-height: 250px; /* 限制最大高度，确保按钮区域可见 */
            height: auto; /* 保持宽高比 */
            border-radius: 5px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            display: inline-block;
            transition: all 0.3s ease;
        }

        /* 图片加载提示 */
        .image-loading {
            color: #666;
            padding: 20px 0;
            display: none;
        }

        /* 上传按钮样式 */
        .upload-container {
            flex: 1;
            min-width: 250px;
            position: relative;
        }

        .upload-btn {
            width: 100%;
            padding: 12px 15px;
            border: 1px dashed #ddd;
            border-radius: 30px;
            font-size: 1rem;
            color: #666;
            background-color: #f9f9f9;
            cursor: pointer;
            transition: all 0.2s ease;
            text-align: left;
        }

        .upload-btn:hover {
            border-color: #e94c89;
            background-color: #fcf4f7;
        }

        .upload-btn i {
            margin-right: 8px;
            color: #e94c89;
        }

        .upload-input {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }

        .file-preview {
            margin-top: 10px;
            max-width: 200px;
            border-radius: 8px;
            display: none;
        }

        .file-info {
            margin-top: 5px;
            font-size: 0.8rem;
            color: #666;
            display: none;
        }

        .remove-file {
            background: none;
            border: none;
            color: #e94c89;
            cursor: pointer;
            margin-left: 5px;
            display: none;
        }

        /* 编辑模态框中的上传样式 */
        .edit-upload-container {
            margin-bottom: 15px;
            position: relative;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .nav-links {
                display: none;
            }

            .mobile-menu-button {
                display: block;
            }

            .mobile-menu.active {
                display: block;
            }

            .title h1 {
                font-size: 1.2rem;
            }

            .add-form {
                flex-direction: column;
            }

            .form-control {
                min-width: auto;
            }

            .form-actions {
                width: 100%;
                justify-content: space-between;
            }

            .stats-filter {
                flex-direction: column;
                align-items: flex-start;
            }

            .filter-buttons {
                width: 100%;
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
            }

            .filter-btn {
                flex: 1;
                min-width: 80px;
                text-align: center;
            }

            .action-btn {
                width: 36px;
                height: 36px;
                font-size: 1.1rem;
            }

            .actions {
                padding: 10px 0;
            }

            /* 移动设备上的弹窗图片调整 */
            .edit-modal-image {
                max-height: 200px;
            }

            /* 列表项使用垂直布局 */
            .cike {
                display: flex;
                flex-direction: column; /* 垂直排列子元素，实现自动换行 */
            }

            /* 内容区与操作区之间添加明显分隔 */
            .cike .content {
                margin-bottom: 12px; /* 内容区底部间距 */
                padding-bottom: 8px;
                border-bottom: 1px dashed #eee; /* 虚线分隔 */
            }

            /* 操作区靠左侧对齐，更符合移动端操作习惯 */
            .actions {
                justify-content: flex-start; /* 左对齐按钮 */
                padding-left: 35px; /* 与内容区文本对齐 */
                width: 100%; /* 占满宽度 */
                flex-wrap: wrap; /* 按钮过多时自动换行 */
            }
        }

        /* 桌面端保持水平布局 */
        @media (min-width: 769px) {
            .cike {
                display: flex;
                align-items: center;
                justify-content: space-between;
            }

            .actions {
                justify-content: flex-end;
            }
        }

        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .cike {
            animation: fadeIn 0.3s ease forwards;
        }

        /* 底部样式 */
        footer {
            text-align: center;
            padding: 30px 0;
            margin-top: 50px;
            color: #999;
            font-size: 0.9rem;
            background-color: white;
            border-top: 1px solid #f0f0f0;
        }

        .footer-links {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin: 15px 0;
        }

        .footer-links a {
            color: #999;
            text-decoration: none;
        }

        .footer-links a:hover {
            color: #e94c89;
        }
    </style>
</head>
<body>
<!-- 导航栏 -->
<nav id="navbar" class="bg-transparent">
    <div class="nav-container">
        <a href="/" class="logo" id="logoText" class="text-dark">恋爱清单</a>
        <div class="hidden md:flex space-x-8">
                <a href="/" class="text-dark hover:text-primary transition-colors py-2">首页</a>
                <a href="/moments" class="text-dark hover:text-primary transition-colors py-2">点点滴滴</a>
                <a href="/photos" class="text-dark hover:text-primary transition-colors py-2">Love Photo</a>
                <a href="/lovelist" class="text-primary border-b-2 border-primary font-medium py-2">Love List</a>
                <a href="/messages" class="text-dark hover:text-primary transition-colors py-2">留言板</a>
                <a href="/couple" class="text-dark hover:text-primary transition-colors py-2">爱情纪念</a>
            </div>
        <div class="user-area">
            <img src="" alt="用户头像" class="user-avatar" id="navUserAvatar">
            <button class="mobile-menu-button" id="mobile-menu-button">
                <i class="fa fa-bars"></i>
            </button>
        </div>
    </div>

    <!-- 移动端菜单 -->
    <div class="mobile-menu" id="mobile-menu" class="hidden md:hidden mt-4 pb-2" >
         <a href="/" class="block text-dark hover:text-primary transition-colors py-2">首页</a>
		<a href="/moments" class="block text-primary font-medium py-2">点点滴滴</a>
		<a href="/photos" class="block text-dark hover:text-primary transition-colors py-2">Love Photo</a>
		<a href="/lovelist" class="block text-dark hover:text-primary transition-colors py-2">Love List</a>
		<a href="/messages" class="block text-dark hover:text-primary transition-colors py-2">留言板</a>
		<a href="/couple" class="block text-dark hover:text-primary transition-colors py-2">爱情纪念</a>
    </div>
</nav>

<div id="pjax-container">
    <div class="central">
        <div class="title">
            <h1>总有些惊奇的际遇 比方说当我遇见你</h1>
        </div>

        <!-- 情侣关系状态 -->
        <div class="relationship-status">
            <div id="single-status">
                <p>你当前没有建立情侣关系，清单仅自己可见</p>
                <button class="btn btn-outline" id="find-partner-btn">寻找伴侣</button>
            </div>
            <div id="couple-status" style="display: none;">
                <p>我们已在一起 <span id="days-together">0</span> 天</p>
                <span class="anniversary-date">恋爱开始于: <span id="anniversary-date">未设置</span></span>
                <div class="couple-info">
                    <img src="" alt="你的头像" class="avatar" id="my-avatar">
                    <i class="fa fa-heart" style="color: #e94c89;"></i>
                    <img src="" alt="伴侣头像" class="avatar" id="partner-avatar">
                </div>
                <div class="couple-names" id="couple-names"></div>
            </div>
        </div>

        <!-- 统计和筛选 -->
        <div class="stats-filter">
            <div class="stats">
                总进度: <span id="total-progress">0</span>% (完成 <span id="completed-count">0</span>/<span id="total-count">0</span>)
            </div>
            <div class="filters filter-buttons">
                <button class="filter-btn active" data-filter="all">全部</button>
                <button class="filter-btn" data-filter="completed">已完成</button>
                <button class="filter-btn" data-filter="pending">未完成</button>
            </div>
        </div>

        <!-- 添加清单表单 -->
        <div class="card">
            <form class="add-form" id="add-love-item-form">
                <input type="text" class="form-control" id="item-content" placeholder="添加你们的恋爱清单... 例如：一起去看一场电影🎬"
                       required>

                <!-- 图片上传区域 -->
                <div class="upload-container">
                    <button type="button" class="upload-btn" id="upload-btn">
                        <i class="fa fa-upload"></i> 上传图片（可选）
                    </button>
                    <input type="file" class="upload-input" id="item-image-upload" accept="image/*">
                    <input type="hidden" id="item-image-url">
                    <img class="file-preview" id="image-preview" src="" alt="预览图">
                    <div class="file-info" id="file-info">
                        已选择: <span id="file-name"></span>
                        <button type="button" class="remove-file" id="remove-file">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                </div>

                <div class="form-actions">
                    <label class="share-checkbox">
                        <input type="checkbox" id="share-item"> 共享给伴侣
                    </label>
                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-plus"></i> 添加
                    </button>
                </div>
            </form>
        </div>

        <!-- 清单列表 -->
        <div class="row central central-800">
            <div class="card col-lg-12 col-md-12 col-sm-12 col-sm-x-12">
                <div class="list_texts animated fadeInUp delay-03s">
                    <ul class="lovelist" id="lovelist-container">
                        <!-- 示例清单项 -->
                        <li class="cike" data-id="sample1">
                            <div class="content">
                                <i class="iconfont icon-weibiaoti1">
                                    <i class="fa fa-circle-o"></i>
                                </i>
                                一起去看日出
                            </div>
                            <div class="actions">
                                <button class="action-btn toggle-complete" title="标记为完成">
                                    <i class="fa fa-check"></i>
                                </button>
                                <button class="action-btn edit-item" title="编辑">
                                    <i class="fa fa-pencil"></i>
                                </button>
                                <button class="action-btn delete-item" title="删除">
                                    <i class="fa fa-trash"></i>
                                </button>
                            </div>
                        </li>
                        <li class="cike completed" data-id="sample2">
                            <div class="content">
                                <i class="iconfont icon-chenggong2">
                                    <i class="fa fa-check-circle"></i>
                                </i>
                                一起看一场电影
                            </div>
                            <div class="actions">
                                <button class="action-btn toggle-complete" title="标记为未完成">
                                    <i class="fa fa-undo"></i>
                                </button>
                                <button class="action-btn edit-item" title="编辑">
                                    <i class="fa fa-pencil"></i>
                                </button>
                                <button class="action-btn delete-item" title="删除">
                                    <i class="fa fa-trash"></i>
                                </button>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 编辑清单模态框 -->
<div class="modal" id="edit-modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">编辑清单</h3>
            <button class="close-modal" id="close-edit-modal"><i class="fa fa-times"></i></button>
        </div>
        <div class="modal-body">
            <form id="edit-form">
                <input type="hidden" id="edit-item-id">
                <input type="text" class="form-control" id="edit-content" placeholder="清单内容" required>
                <br>

                <!-- 编辑模态框中的图片上传区域 -->
                <div class="edit-upload-container">
                    <button type="button" class="upload-btn" id="edit-upload-btn">
                        <i class="fa fa-upload"></i> 上传图片（可选）
                    </button>
                    <input type="file" class="upload-input" id="edit-image-upload" accept="image/*">
                    <input type="hidden" id="edit-image-url">
                    <input type="hidden" id="edit-original-image-url">

                    <!-- 优化的图片展示容器 -->
                    <div class="edit-image-container" id="edit-image-container" style="display: none;">
                        <div class="image-loading" id="edit-image-loading">
                            <i class="fa fa-spinner fa-spin"></i> 加载中...
                        </div>
                        <img class="edit-modal-image" id="edit-image-preview" src="" alt="预览图">
                        <!-- 新增：图片删除按钮 -->
                        <button type="button" class="delete-image-btn" id="delete-image-btn" title="删除图片">
                            <i class="fa fa-trash"></i>
                        </button>
                        <div class="image-delete-confirm" id="image-delete-confirm">
                            <i class="fa fa-info-circle"></i> 图片将彻底删除
                        </div>
                    </div>

                    <div class="file-info" id="edit-file-info">
                        已选择: <span id="edit-file-name"></span>
                        <button type="button" class="remove-file" id="edit-remove-file">
                            <i class="fa fa-times"></i>
                        </button>
                    </div>
                </div>

                <label class="share-checkbox">
                    <input type="checkbox" id="edit-share"> 共享给伴侣
                </label>
            </form>
        </div>
        <div class="modal-footer">
            <button class="btn btn-outline" id="cancel-edit">取消</button>
            <button class="btn btn-primary" id="save-edit">保存</button>
        </div>
    </div>
</div>

<!-- 确认删除模态框 -->
<div class="modal" id="delete-modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">确认删除</h3>
            <button class="close-modal" id="close-delete-modal">&times;</button>
        </div>
        <div class="modal-body">
            <p>确定要删除这个清单项吗？此操作不可恢复。</p>
            <input type="hidden" id="delete-item-id">
        </div>
        <div class="modal-footer">
            <button class="btn btn-outline" id="cancel-delete">取消</button>
            <button class="btn btn-primary" id="confirm-delete">删除</button>
        </div>
    </div>
</div>

<footer>
    <p>爱情小窝 &copy; 2025</p>
    <!--
    <div class="footer-links">
        <a href="/about">关于我们</a>
        <a href="/privacy">隐私政策</a>
        <a href="/terms">使用条款</a>
        <a href="/contact">联系我们</a>
    </div>
    -->
    <p>总有些惊奇的际遇 比方说当我遇见你</p>
</footer>

<script src="/Style/js/jquery.min.v3.6.0 .js"></script>
<script>
    // 全局变量
    let loveItems = [];
    let inRelationship = false;
    let currentFilter = 'all';
    let anniversaryDate = null;
    let currentUser = null;

    // API基础路径
    const API_BASE = '/api';

    // 页面加载完成后初始化
    $(document).ready(function() {
        // 检查登录状态 - 确保先获取用户信息
        checkLoginStatus(function() {
            // 初始化导航栏滚动效果
            initNavbarScroll();

            // 初始化移动端菜单
            initMobileMenu();

            // 加载情侣关系状态 - 放在回调中执行，确保currentUser已初始化
            loadRelationshipStatus();

            // 加载恋爱清单
            loadLoveItems();

            // 加载统计数据
            loadStatistics();

            // 初始化文件上传事件监听
            initUploadEventListeners();

            // 初始化其他事件监听
            initEventListeners();
            // 初始化图片删除相关事件监听
            initImageDeleteEventListeners();
        });
    });

    // 初始化移动端菜单
    function initMobileMenu() {
        const mobileMenuButton = $('#mobile-menu-button');
        const mobileMenu = $('#mobile-menu');

        // 点击菜单按钮切换显示状态
        mobileMenuButton.click(function(e) {
            e.stopPropagation();
            mobileMenu.toggleClass('active');
        });

        // 点击菜单项后关闭菜单
        mobileMenu.find('a').click(function() {
            mobileMenu.removeClass('active');
        });

        // 点击页面其他地方关闭菜单
        $(document).click(function(e) {
            if (!mobileMenu.is(e.target) && mobileMenu.has(e.target).length === 0 &&
                !mobileMenuButton.is(e.target) && mobileMenuButton.has(e.target).length === 0) {
                mobileMenu.removeClass('active');
            }
        });
    }

    // 初始化图片删除相关事件监听
    function initImageDeleteEventListeners() {
        // 图片删除按钮点击事件
        $('#delete-image-btn').click(function() {
            // 确认删除
            if (confirm('确定要删除这张图片吗？')) {
                const originalImageUrl = $('#edit-original-image-url').val();

                // 如果是已保存的图片（不是新上传尚未保存的），标记为待删除
                if (originalImageUrl && originalImageUrl.trim() !== '') {
                    // 显示确认信息
                    $('#image-delete-confirm').show();
                    // 清空图片URL但保留原始URL用于删除
                    $('#edit-image-url').val('');
                    // 隐藏图片，显示占位符
                    $('#edit-image-preview').hide();
                    $('#edit-image-loading').text('图片将被删除');
                    $('#edit-image-loading').show();
                    // 禁用删除按钮
                    $('#delete-image-btn').prop('disabled', true);
                } else {
                    // 对于新上传尚未保存的图片，直接重置
                    resetFileUpload('#edit-image-preview', '#edit-file-name', '#edit-file-info', '#edit-remove-file', '#edit-image-url');
                    $('#edit-image-container').hide();
                }
            }
        });
    }

    // 初始化文件上传相关事件监听
    function initUploadEventListeners() {
        // 添加表单的文件上传
        $('#item-image-upload').change(function(e) {
            handleFileUpload(e, '#image-preview', '#file-name', '#file-info', '#remove-file', '#item-image-url');
        });

        $('#upload-btn').click(function() {
            $('#item-image-upload').click();
        });

        $('#remove-file').click(function() {
            resetFileUpload('#image-preview', '#file-name', '#file-info', '#remove-file', '#item-image-url');
        });

        // 编辑模态框的文件上传
        $('#edit-image-upload').change(function(e) {
            // 显示加载状态
            $('#edit-image-loading').show();
            $('#edit-image-preview').hide();

            handleFileUpload(e, '#edit-image-preview', '#edit-file-name', '#edit-file-info', '#edit-remove-file', '#edit-image-url', function() {
                // 上传完成后隐藏加载状态，显示图片
                $('#edit-image-loading').hide();
                $('#edit-image-preview').show();
                $('#edit-image-container').show();
            });
        });

        $('#edit-upload-btn').click(function() {
            $('#edit-image-upload').click();
        });

        $('#edit-remove-file').click(function() {
            resetFileUpload('#edit-image-preview', '#edit-file-name', '#edit-file-info', '#edit-remove-file', '#edit-image-url');
            $('#edit-image-container').hide();
        });
    }

    // 处理文件上传 - 添加回调函数
    function handleFileUpload(event, previewSelector, nameSelector, infoSelector, removeSelector, urlInputSelector, callback) {
        const file = event.target.files[0];
        if (!file) return;

        // 检查文件类型
        if (!file.type.startsWith('image/')) {
            alert('请上传图片文件');
            if (callback) callback();
            return;
        }

        // 显示文件名
        $(nameSelector).text(file.name);
        $(infoSelector).show();
        $(removeSelector).show();

        // 显示预览图
        const reader = new FileReader();
        reader.onload = function(e) {
            $(previewSelector).attr('src', e.target.result);
            $(previewSelector).show();
            if (callback) callback();
        }
        reader.readAsDataURL(file);

        // 上传文件到服务器
        const formData = new FormData();
        formData.append('file', file);

        $.ajax({
            url: `${API_BASE}/upload`,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(data) {
                if (data.status === 'success') {
                    // 保存返回的图片URL
                    $(urlInputSelector).val(data.url);
                } else {
                    alert('上传失败: ' + (data.message || '未知错误'));
                    resetFileUpload(previewSelector, nameSelector, infoSelector, removeSelector, urlInputSelector);
                }
            },
            error: function() {
                alert('上传失败，请重试');
                resetFileUpload(previewSelector, nameSelector, infoSelector, removeSelector, urlInputSelector);
            }
        });
    }

    // 重置文件上传区域
    function resetFileUpload(previewSelector, nameSelector, infoSelector, removeSelector, urlInputSelector) {
        // 清空文件输入
        const fileInput = $(previewSelector).closest('.upload-container').find('.upload-input');
        fileInput.val('');

        // 隐藏预览和信息
        $(previewSelector).hide();
        $(previewSelector).attr('src', '');
        $(nameSelector).text('');
        $(infoSelector).hide();
        $(removeSelector).hide();

        // 清空URL
        $(urlInputSelector).val('');
    }

    // 检查登录状态，添加回调函数
    function checkLoginStatus(callback) {
        $.get('/api/user', function (data) {
            if (data.id) {
                currentUser = data;
                // 更新导航栏头像
                $('#navUserAvatar').attr('src', currentUser.avatar || 'default_avatar.jpg');
                // 更新页面标题和logo
                updatePageIdentifiers();

                // 执行回调函数
                if (callback) callback();
            } else {
                window.location.href = '/login';
            }
        }).fail(function () {
            window.location.href = '/login';
        });
    }

    // 初始化导航栏滚动效果
    function initNavbarScroll() {
        window.onscroll = function () {
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            const navbar = document.getElementById('navbar');
            const logo = document.querySelector('.logo');
            const navLinks = document.querySelectorAll('.nav-links a');
            const mobileMenuButton = document.querySelector('.mobile-menu-button');

            if (scrollTop > 50) {
                navbar.classList.add('bg-white', 'shadow-md');
                navbar.classList.remove('bg-transparent');

                logo.classList.remove('text-white');
                logo.classList.add('text-dark');

                navLinks.forEach(item => {
                    item.classList.remove('text-white');
                    item.classList.add('text-dark');
                });

                if (mobileMenuButton) {
                    mobileMenuButton.classList.remove('text-white');
                    mobileMenuButton.classList.add('text-dark');
                }
            } else {
                navbar.classList.remove('bg-white', 'shadow-md');
                navbar.classList.add('bg-transparent');

                logo.classList.add('text-white');
                logo.classList.remove('text-dark');

                navLinks.forEach(item => {
                    item.classList.add('text-white');
                    item.classList.remove('text-dark');
                });

                if (mobileMenuButton) {
                    mobileMenuButton.classList.add('text-white');
                    mobileMenuButton.classList.remove('text-dark');
                }
            }
        };

        // 初始触发一次滚动事件
        window.onscroll();
    }

    // 更新页面标题和标识
    function updatePageIdentifiers() {
        if (!currentUser) return;

        const myName = currentUser.nickname || currentUser.username;

        // 更新页面标题
        document.title = `${myName}的恋爱清单 | 总有些惊奇的际遇 比方说当我遇见你`;

        // 更新logo文本
        $('#logoText').text(`${myName}的小窝`);
    }

    // 加载情侣关系状态
    function loadRelationshipStatus() {
        $.get(`${API_BASE}/couple/relationship`, function(data) {
            inRelationship = data.in_relationship;

            if (inRelationship) {
                // 显示情侣状态
                $('#single-status').hide();
                $('#couple-status').show();

                // 更新数据
                $('#days-together').text(data.relationship.days_together);
                $('#my-avatar').attr('src', currentUser.avatar || 'default_avatar.jpg');
                $('#partner-avatar').attr('src', data.partner.avatar || 'default_avatar.jpg');
                $('#couple-names').text(`${currentUser.nickname || currentUser.username} 和 ${data.partner.nickname || data.partner.username}`);

                // 更新导航栏头像
                $('#navUserAvatar').attr('src', currentUser.avatar || 'default_avatar.jpg');

                // 更新页面标识
                updatePageIdentifiersWithPartner(data.partner);

                // 获取并显示纪念日
                fetchAnniversary();

                // 启用共享选项
                $('#share-item').prop('disabled', false);
            } else {
                // 显示单身状态
                $('#couple-status').hide();
                $('#single-status').show();

                // 禁用共享选项
                $('#share-item').prop('disabled', true);
                $('#share-item').prop('checked', false);
            }
        }).fail(function() {
            console.error('加载情侣关系状态失败');
        });
    }

    // 带伴侣信息的页面标识更新
    function updatePageIdentifiersWithPartner(partner) {
        if (!currentUser) return;

        const myName = currentUser.nickname || currentUser.username;
        const partnerName = partner.nickname || partner.username;

        // 更新页面标题
        document.title = `${myName}和${partnerName}的恋爱清单 | 总有些惊奇的际遇`;

        // 更新logo文本
        $('#logoText').text(`${myName}❤️${partnerName}`);
    }

    // 获取纪念日信息
    function fetchAnniversary() {
        $.get('/api/anniversaries', function (data) {
            // 查找恋爱开始日
            const loveAnniversary = data.find(item => item.type === 'love_start');

            if (loveAnniversary) {
                // 找到恋爱开始日
                anniversaryDate = new Date(loveAnniversary.date);
                $('#anniversary-date').text(loveAnniversary.date);

                // 启动倒计时更新
                updateAnniversaryTime();
            } else {
                // 没有找到恋爱开始日
                anniversaryDate = null;
                $('#anniversary-date').text("未设置");
            }
        }).fail(function () {
            console.error('获取纪念日失败');
            $('#anniversary-date').text("加载失败");
        });
    }

    // 更新纪念日时间显示
    function updateAnniversaryTime() {
        if (!anniversaryDate) return;

        const now = new Date();
        const timeDiff = now - anniversaryDate;

        // 计算天数
        const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));

        // 更新显示
        $('#days-together').text(days);

        // 每秒更新一次
        setTimeout(updateAnniversaryTime, 1000);
    }

    // 加载恋爱清单
    function loadLoveItems() {
        $.get(`${API_BASE}/love-list`, function(data) {
            loveItems = data;
            renderLoveList();
        }).fail(function() {
            alert('加载清单失败，请刷新页面重试');
        });
    }

    // 加载统计数据
    function loadStatistics() {
        $.get(`${API_BASE}/love-list/statistics`, function(data) {
            $('#total-count').text(data.total);
            $('#completed-count').text(data.completed);
            $('#total-progress').text(data.progress);
        }).fail(function() {
            console.error('加载统计数据失败');
        });
    }

    // 渲染清单列表
    function renderLoveList() {
        const container = $('#lovelist-container');
        container.empty();

        if (loveItems.length === 0) {
            // 添加示例项
            container.html(`
                <li class="cike" data-id="sample1">
                    <div class="content">
                        <i class="iconfont icon-weibiaoti1">
                            <i class="fa fa-circle-o"></i>
                        </i>
                        示例：一起去看日出
                    </div>
                    <div class="actions">
                        <button class="action-btn toggle-complete" title="标记为完成">
                            <i class="fa fa-check"></i>
                        </button>
                        <button class="action-btn edit-item" title="编辑">
                            <i class="fa fa-pencil"></i>
                        </button>
                        <button class="action-btn delete-item" title="删除">
                            <i class="fa fa-trash"></i>
                        </button>
                    </div>
                </li>
                <li class="cike completed" data-id="sample2">
                    <div class="content">
                        <i class="iconfont icon-chenggong2">
                            <i class="fa fa-check-circle"></i>
                        </i>
                        示例：一起看一场电影
                    </div>
                    <div class="actions">
                        <button class="action-btn toggle-complete" title="标记为未完成">
                            <i class="fa fa-undo"></i>
                        </button>
                        <button class="action-btn edit-item" title="编辑">
                            <i class="fa fa-pencil"></i>
                        </button>
                        <button class="action-btn delete-item" title="删除">
                            <i class="fa fa-trash"></i>
                        </button>
                    </div>
                </li>
            `);
            return;
        }

        // 根据筛选条件过滤
        let filteredItems = loveItems;
        if (currentFilter === 'completed') {
            filteredItems = loveItems.filter(item => item.is_completed);
        } else if (currentFilter === 'pending') {
            filteredItems = loveItems.filter(item => !item.is_completed);
        }

        filteredItems.forEach(item => {
            const isCompleted = item.is_completed;
            const hasImage = item.image_url && item.image_url.trim() !== '';

            const listItem = $(`
                <li class="cike ${isCompleted ? 'completed' : ''}" data-id="${item.id}">
                    <div class="content">
                        <i class="iconfont ${isCompleted ? 'icon-chenggong2' : 'icon-weibiaoti1'}">
                            ${isCompleted ? '<i class="fa fa-check-circle"></i>' : '<i class="fa fa-circle-o"></i>'}
                        </i>
                        ${item.content}
                    </div>
                    <div class="actions">
                        <button class="action-btn toggle-complete" title="${isCompleted ? '标记为未完成' : '标记为完成'}">
                            ${isCompleted ? '<i class="fa fa-undo"></i>' : '<i class="fa fa-check"></i>'}
                        </button>
                        <button class="action-btn edit-item" title="编辑">
                            <i class="fa fa-pencil"></i>
                        </button>
                        <button class="action-btn delete-item" title="删除">
                            <i class="fa fa-trash"></i>
                        </button>
                        <button class="action-btn view-image" title="查看图片">
                        ${hasImage ? `<i class="fa fa-picture-o" style="color: #e94c89;"></i>` : ''}
                        </button>
                    </div>
                </li>
                ${hasImage ? `
                <ul class="image-preview" style="display: none;">
                    <li>
                        <img src="${item.image_url}" alt="${item.content}" class="spotlight">
                    </li>
                </ul>
                ` : ''}
            `);

            container.append(listItem);
        });
    }

    // 初始化其他事件监听
    function initEventListeners() {
        // 添加新项表单提交
        $('#add-love-item-form').submit(function(e) {
            e.preventDefault();
            addLoveItem();
        });

        // 筛选按钮点击
        $('.filter-btn').click(function() {
            $('.filter-btn').removeClass('active');
            $(this).addClass('active');
            currentFilter = $(this).data('filter');
            renderLoveList();
        });

        // 清单项点击（展开/收起图片）
        $(document).on('click', '.cike', function(e) {
            // 排除点击操作按钮的情况
            if (!$(e.target).closest('.actions').length) {
                $(this).next('.image-preview').slideToggle(300);
            }
        });

        // 切换完成状态
        $(document).on('click', '.toggle-complete', function(e) {
            e.stopPropagation();
            const itemId = $(this).closest('.cike').data('id');
            toggleCompleteStatus(itemId);
        });

        // 编辑按钮点击
        $(document).on('click', '.edit-item', function(e) {
            e.stopPropagation();
            const itemId = $(this).closest('.cike').data('id');
            openEditModal(itemId);
        });

        // 删除按钮点击
        $(document).on('click', '.delete-item', function(e) {
            e.stopPropagation();
            const itemId = $(this).closest('.cike').data('id');
            openDeleteModal(itemId);
        });

        // 关闭编辑模态框
        $('#close-edit-modal, #cancel-edit').click(function() {
            $('#edit-modal').removeClass('show');
            // 重置编辑模态框中的上传区域
            resetFileUpload('#edit-image-preview', '#edit-file-name', '#edit-file-info', '#edit-remove-file', '#edit-image-url');
            $('#edit-image-container').hide();
        });

        // 保存编辑
        $('#save-edit').click(function() {
            saveEdit();
        });

        // 关闭删除模态框
        $('#close-delete-modal, #cancel-delete').click(function() {
            $('#delete-modal').removeClass('show');
        });

        // 确认删除
        $('#confirm-delete').click(function() {
            confirmDelete();
        });

        // 寻找伴侣按钮
        $('#find-partner-btn').click(function() {
            window.location.href = '/couple';
        });
    }

    // 添加新的恋爱清单项
    function addLoveItem() {
        const content = $('#item-content').val().trim();
        const imageUrl = $('#item-image-url').val().trim();
        const isShared = inRelationship ? $('#share-item').is(':checked') : false;

        if (!content) {
            alert('请输入清单内容');
            return;
        }

        $.ajax({
            url: `${API_BASE}/love-list`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                content: content,
                image_url: imageUrl,
                is_shared: isShared
            }),
            success: function() {
                // 清空表单
                $('#item-content').val('');
                $('#share-item').prop('checked', false);
                // 重置上传区域
                resetFileUpload('#image-preview', '#file-name', '#file-info', '#remove-file', '#item-image-url');

                // 重新加载数据
                loadLoveItems();
                loadStatistics();

                // 提示成功
                alert('添加成功！');
            },
            error: function(xhr) {
                const errorMsg = xhr.responseJSON?.message || '添加失败，请重试';
                alert(errorMsg);
            }
        });
    }

    // 切换完成状态
    function toggleCompleteStatus(itemId) {
        const item = loveItems.find(i => i.id === itemId);
        if (!item) return;

        $.ajax({
            url: `${API_BASE}/love-list/${itemId}`,
            type: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify({
                is_completed: !item.is_completed
            }),
            success: function() {
                loadLoveItems();
                loadStatistics();
            },
            error: function() {
                alert('操作失败，请重试');
            }
        });
    }

    // 修改打开编辑模态框的函数
    function openEditModal(itemId) {
        const item = loveItems.find(i => i.id === itemId);
        if (!item) return;

        $('#edit-item-id').val(itemId);
        $('#edit-content').val(item.content);
        $('#edit-share').prop('checked', item.is_shared);
        $('#edit-share').prop('disabled', !inRelationship);

        // 处理图片
        const imageUrl = item.image_url || '';
        $('#edit-image-url').val(imageUrl);
        $('#edit-original-image-url').val(imageUrl); // 保存原始图片URL

        // 重置图片删除相关状态
        $('#image-delete-confirm').hide();
        $('#delete-image-btn').prop('disabled', false);

        // 隐藏图片容器
        $('#edit-image-container').hide();

        if (imageUrl) {
            // 显示加载状态
            $('#edit-image-loading').show();
            $('#edit-image-preview').hide();
            $('#edit-image-container').show();

            // 创建新图像对象来检测加载完成
            const img = new Image();
            img.onload = function() {
                // 图片加载完成后显示
                $('#edit-image-preview').attr('src', imageUrl);
                $('#edit-image-loading').hide();
                $('#edit-image-preview').show();
            };
            img.onerror = function() {
                // 图片加载失败
                $('#edit-image-loading').text('图片加载失败');
                setTimeout(() => {
                    $('#edit-image-container').hide();
                }, 2000);
            };
            img.src = imageUrl;

            $('#edit-file-name').text(imageUrl.split('/').pop());
            $('#edit-file-info').show();
            $('#edit-remove-file').show();
        } else {
            resetFileUpload('#edit-image-preview', '#edit-file-name', '#edit-file-info', '#edit-remove-file', '#edit-image-url');
        }

        $('#edit-modal').addClass('show');
    }

    // 保存编辑
    function saveEdit() {
        const itemId = $('#edit-item-id').val();
        const content = $('#edit-content').val().trim();
        const newImageUrl = $('#edit-image-url').val().trim();
        const originalImageUrl = $('#edit-original-image-url').val().trim();
        const isShared = inRelationship ? $('#edit-share').is(':checked') : false;

        if (!content) {
            alert('请输入清单内容');
            return;
        }

        // 准备要执行的操作：先删除图片（如果需要），再更新清单
        const operations = [];

        // 如果原始始图片存在且新图片URL为空，需要删除原始图片
        if (originalImageUrl && originalImageUrl.trim() !== '' && !newImageUrl) {
            // 从URL中提取文件名
            let filename = '';
            try {
                // 分割URL获取文件名
                const urlParts = originalImageUrl.split('/');
                filename = urlParts[urlParts.length - 1];

                // 验证文件名不为空
                if (!filename) {
                    throw new Error('无法提取提取文件名');
                }

                // 添加删除图片的操作
                operations.push(new Promise((resolve, reject) => {
                    $.ajax({
                        url: `${API_BASE}/upload/${filename}`,
                        type: 'DELETE',
                        success: function() {
                            resolve();
                        },
                        error: function(xhr) {
                            console.error('删除图片失败', xhr);
                            // 即使删除图片失败，仍然继续更新清单，但显示警告
                            alert('清单已更新，但删除图片时出现错误: ' + (xhr.responseJSON?.message || '未知错误'));
                            resolve();
                        }
                    });
                }));
            } catch (error) {
                console.error('处理文件名时出错:', error);
                alert('准备删除图片时出错: ' + error.message);
            }
        }

        // 执行所有操作后更新清单
        Promise.all(operations).then(() => {
            // 更新清单数据
            $.ajax({
                url: `${API_BASE}/love-list/${itemId}`,
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify({
                    content: content,
                    image_url: newImageUrl,
                    is_shared: isShared
                }),
                success: function() {
                    $('#edit-modal').removeClass('show');
                    // 重置上传区域
                    resetFileUpload('#edit-image-preview', '#edit-file-name', '#edit-file-info', '#edit-remove-file', '#edit-image-url');
                    $('#edit-image-container').hide();
                    loadLoveItems();
                    alert('更新成功！');
                },
                error: function(xhr) {
                    const errorMsg = xhr.responseJSON?.message || '更新失败，请重试';
                    alert(errorMsg);
                }
            });
        });
    }

    // 打开删除模态框
    function openDeleteModal(itemId) {
        $('#delete-item-id').val(itemId);
        $('#delete-modal').addClass('show');
    }

    // 确认删除
    function confirmDelete() {
        const itemId = $('#delete-item-id').val();

        $.ajax({
            url: `${API_BASE}/love-list/${itemId}`,
            type: 'DELETE',
            success: function() {
                $('#delete-modal').removeClass('show');
                loadLoveItems();
                loadStatistics();
                alert('删除成功！');
            },
            error: function() {
                alert('删除失败，请重试');
            }
        });
    }
</script>
</body>
</html>
